﻿using System;
using System.Data;
using System.Data.OracleClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class CostManage_CostApproval : UserPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Dep_Bind();
            Auth();
            SetPager();
            SetEDPager();
        }
    }

    private void Dep_Bind()
    {
        string sqlstr = "SELECT DISTINCT SUBSTR(Replace(CELL_CHNAME,'G',''),0,2) AS County FROM CELL_CLASS ORDER BY SUBSTR(Replace(CELL_CHNAME,'G',''),0,2)";
        Dep_A.DataSource = OracleHelper.ExecuteDataSet(sqlstr, CommandType.Text, null).Tables[0].DefaultView;
        Dep_A.DataTextField = "County";
        Dep_A.DataValueField = "County";
        Dep_A.DataBind();
        Dep_A.Items.Insert(0, new ListItem("全市", "0"));
    }

    private void Auth()
    {
        DataRow dr = GetOrganAndCompany().Rows[0];
        if ((!dr["company"].ToString().Equals("延安")) || dr["organ"].ToString().Equals("宝塔维护站"))
        {
            Dep_A.SelectedValue = dr["company"].ToString();
        }
        else
        {
            Dep_A.Enabled = true;
        }
    }

    private void SetPager()
    {
        PagedDataSource pds = new PagedDataSource();
        DataSet ds = GetApproval();
        ApprovalPager.RecordCount = ds.Tables[0].Rows.Count;
        pds.DataSource = ds.Tables[0].DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = ApprovalPager.PageSize;
        pds.CurrentPageIndex = ApprovalPager.CurrentPageIndex - 1;
        ApprovalList.DataSource = pds;
        ApprovalList.DataBind();
    }

    private void SetEDPager()
    {
        PagedDataSource pds = new PagedDataSource();
        DataSet ds = GetApprovaled();
        AppedPager.RecordCount = ds.Tables[0].Rows.Count;
        pds.DataSource = ds.Tables[0].DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = AppedPager.PageSize;
        pds.CurrentPageIndex = AppedPager.CurrentPageIndex - 1;
        AppedList.DataSource = pds;
        AppedList.DataBind();
    }

    private DataSet GetApproval()
    {
        string sqlStr = @"select order_no,t1.organ,t1.physical_name,t2.meterway,t1.rating_fee,t1.realpay,t1.input_date
                                            ,t1.read_date,t1.meter_now,t1.last_meter
                                  from U_METER_PAY_T t1
                                 inner join u_physical_location_t t2
                                    on t1.physical_name = t2.physical_name
                                   and t2.status = '正常'
                                 where t1.status = '正在申请' ";
        if (Dep_A.SelectedValue != "0")
        {
            sqlStr += " and t1.Organ = '" + Dep_A.SelectedValue + "'";
        }
        if (Cell_CHName_A.Text.Trim().Length > 0)
        {
            sqlStr += " and t1.PHYSICAL_NAME like '%" + Tools.ReplaceString(Cell_CHName_A.Text.Trim(), 50) + "%'";
        }
        sqlStr += " order by input_date";
        return OracleHelper.ExecuteDataSet(sqlStr, CommandType.Text, null);
    }

    private DataSet GetApprovaled()
    {
        string sqlStr = @"SELECT ORDER_NO,PHYSICAL_NAME
                                   ,INPUT_DATE,realpay,MODIFY_DATE,STATUS
                              FROM U_METER_PAY_T WHERE STATUS IN ('审核通过','已被驳回') ";
        if (Dep_A.SelectedValue != "0")
        {
            sqlStr += " and Organ = '" + Dep_A.SelectedValue + "'";
        }
        if (Cell_CHName_A.Text.Trim().Length > 0)
        {
            sqlStr += " and PHYSICAL_NAME like '%" + Tools.ReplaceString(Cell_CHName_A.Text.Trim(), 50) + "%'";
        }
        sqlStr += " order by MODIFY_DATE desc";
        return OracleHelper.ExecuteDataSet(sqlStr, CommandType.Text, null);
    }

    protected void QueryLocation_Click(object sender, EventArgs e)
    {
        SetPager();
        SetEDPager();
    }

    protected void ApprovalPager_PageChanged(object sender, EventArgs e)
    {
        SetPager();
    }

    protected void AppedPager_PageChanged(object sender, EventArgs e)
    {
        SetEDPager();
    }

    protected void Approval_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Show")
        {
            MeterMoreBind(e.CommandArgument.ToString());
            Page.ClientScript.RegisterStartupScript(this.GetType(), "open"
            , "$(function() {$('#MeterDiv').dialog('open');})", true);
        }
        else if (e.CommandName == "Approval")
        {
            Meter_APPr(e.CommandArgument.ToString());
            SetPager();
            SetEDPager();
            JQueryAlert("电费已审核通过！");
        }
        else if (e.CommandName == "Reback")
        {
            Meter_Back(e.CommandArgument.ToString());
            SetPager();
            SetEDPager();
            JQueryAlert("电费审核已退回！");
        }
    }

    private void MeterMoreBind(string argName)
    {
        string sqlStr = @"select order_no,t1.physical_name,meter_now,peak_meter,valley_meter,usual_price,peak_price
                                   ,valley_price,remain_meter,pay_date,read_date,agree_fee,VAT,FARE
                                   ,loss_meter,ifair,rating_fee,realpay,fee_remark,input_date,inputer,last_meter
                                   ,last_peak,last_valley,last_read,last_remain,last_pay,organ,t2.meterway,t2.billing_way
                              from U_METER_PAY_T T1
                              left join U_PHYSICAL_LOCATION_T T2
                                on T1.PHYSICAL_NAME = T2.PHYSICAL_NAME
                             where order_no =:ORDER_NO";
        OracleParameter[] _params = {
                    new OracleParameter(":ORDER_NO",OracleType.VarChar,16)
                };
        _params[0].Value = argName;
        DataRow dr = OracleHelper.ExecuteDataSet(sqlStr, CommandType.Text, _params).Tables[0].Rows[0];
        PHYSICAL_NAME.Text = dr["physical_name"].ToString();
        METERWAY.Text = dr["meterway"].ToString();
        Billing_Way.Text = dr["billing_way"].ToString();
        if (dr["meterway"].ToString().Contains("协定"))
        {
            Agree_Fee.Text = dr["agree_fee"].ToString();
            Last_Pay.Text = DateTime.Parse(dr["last_pay"].ToString()).ToShortDateString();
        }
        else
        {
            Meter_Now.Text = dr["METER_NOW"].ToString();
            Meter_Last.Text = dr["last_meter"].ToString();
            USUAL_PRICE.Text = dr["usual_price"].ToString();
            Loss_Meter.Text = dr["loss_meter"].ToString();
            IFAir.SelectedValue = dr["ifair"].ToString();
            Read_Date.Text = DateTime.Parse(dr["READ_DATE"].ToString()).ToShortDateString();
            Last_Date.Text = DateTime.Parse(dr["last_read"].ToString()).ToShortDateString();
            Rating_Fee.Text = dr["rating_fee"].ToString();
            if (dr["PEAK_METER"].ToString().Length > 0)
            {
                PEAK_METER.Text = dr["PEAK_METER"].ToString();
                PEAK_PRICE.Text = dr["peak_price"].ToString();
                VALLEY_METER.Text = dr["VALLEY_METER"].ToString();
                VALLEY_PRICE.Text = dr["valley_price"].ToString();
                PEAK_METER_Last.Text = dr["PEAK_METER_L"].ToString();
                VALLEY_METER_Last.Text = dr["VALLEY_METER_L"].ToString();
            }
            if (dr["meterway"].ToString().Contains("预付费"))
            {
                REMAIN_METER.Text = dr["REMAIN_METER"].ToString();
                Last_Remain.Text = dr["last_remain"].ToString();
            }
        }
        Pay_Date.Text = DateTime.Parse(dr["PAY_DATE"].ToString()).ToShortDateString();
        RealPay.Text = dr["realpay"].ToString();
        VAT.Text = dr["VAT"].ToString();
        FARE.Text = dr["FARE"].ToString();
        Fee_Remark.Text = dr["FEE_REMARK"].ToString();
    }

    private void Meter_APPr(string argNo)
    {
        string sqlStr = @"UPDATE U_METER_PAY_T SET STATUS='审核通过',MODIFY_DATE=SYSDATE,MODIFYER=:MODIFYER
                                 WHERE ORDER_NO=:ORDER_NO";
        OracleParameter[] _params = {
            new OracleParameter(":MODIFYER",OracleType.VarChar,16),
            new OracleParameter(":ORDER_NO",OracleType.VarChar,16)
        };
        _params[0].Value = LoginUser;
        _params[1].Value = argNo;
        OracleHelper.ExecuteNonQuery(sqlStr, CommandType.Text, _params);
    }

    private void Meter_Back(string argNo)
    {
        string sqlStr = @"UPDATE U_METER_PAY_T SET STATUS='已被驳回',MODIFY_DATE=SYSDATE,MODIFYER=:MODIFYER
                                 WHERE ORDER_NO=:ORDER_NO";
        OracleParameter[] _params = {
            new OracleParameter(":MODIFYER",OracleType.VarChar,16),
            new OracleParameter(":ORDER_NO",OracleType.VarChar,16)
        };
        _params[0].Value = LoginUser;
        _params[1].Value = argNo;
        OracleHelper.ExecuteNonQuery(sqlStr, CommandType.Text, _params);
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }

    protected void Excel_Click(object sender, EventArgs e)
    {
        DataSet ds = GetApproval();
        if (ds.Tables[0].Rows.Count > 65535)
        {
            JQueryAlert("电费申请总数已超过EXCEL最大限制65535行！\\n请缩小查询范围后再尝试导出！");
            return;
        }
        ApprovalList.DataSource = ds;
        ApprovalList.AllowPaging = false;
        ApprovalList.DataBind();
        Tools.DGToExcel(ApprovalList, Dep_A.Enabled ? "UTF-8" : "GB2312");
        SetPager();
    }

    protected void Approval_Click(object sender, EventArgs e)
    {
        string[] rids = null;
        string ridStr = HidRID.Value.Trim().TrimEnd(',');
        if (ridStr.Length > 0)
        {
            rids = ridStr.Split(',');
        }
        HidRID.Value = "";
        string sqlStr = @"UPDATE U_METER_PAY_T SET Status = '审核通过',MODIFY_DATE=SYSDATE,MODIFYER=:MODIFYER
                        WHERE ORDER_NO=:ORDER_NO";
        OracleParameter[] _params = {
            new OracleParameter(":ORDER_NO",OracleType.VarChar,16),
            new OracleParameter(":MODIFYER",OracleType.VarChar,16)
        };
        _params[1].Value = LoginUser;
        for (int i = 0; i < rids.Length; i++)
        {
            _params[0].Value = rids[i];
            OracleHelper.ExecuteNonQuery(sqlStr, CommandType.Text, _params);
        }
        JQueryAlert("审核完成！");
        SetPager();
        SetEDPager();
    }
}
